package stv5.tests;

import java.io.IOException;
import java.net.URLEncoder;

import us.danlib.net.TcpComms;

/**
 * A VERY simple HTTP class
 * @author Daniel
 *
 */
public class HTTP {
	public static String get(String host, String url) throws IOException {
		return get(host, 80, url);
	}
	public static String get(String host, int port, String url) throws IOException {
		TcpComms comms = new TcpComms(host, port);
		
		String req = "GET " + URLEncoder.encode(url,"UTF-8") + " HTTP/1.0\r\n\r\n";		
		comms.send(req);		
		comms.flush();

		// wait
		while (!comms.hasReceived()) {}
		
		// ignore headers, except for Content-Length
		String line = "-";
		String[] tmp;
		int contentLength = 0;		
		while (!"".equals(line.trim())) {
			line = comms.readLine();
			tmp = line.split(": ");
			if (tmp.length == 2 && "Content-Length".equals(tmp[0])) {
				contentLength = Integer.parseInt(tmp[1].trim());
			}
		}		
		return comms.read(contentLength);
	}
}
